<template>
  <div class="app-container">
    <el-card>
      <div class="header-actions">
        <el-button :icon="Back" type="primary" plain @click="goBack">返回</el-button>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="个人资料" name="personal">
          <div class="doctor-info">
            <div class="avatar-section">
              <el-upload class="avatar-uploader" action="/api/doctor/upload" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/png,image/jpg">
                <el-image v-if="doctorInfo.imgurl" :src="doctorInfo.imgurl" class="avatar" fit="cover"
                  style="width: 100px; height: 100px; border-radius: 50%">
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-slot">
                      <el-icon>
                        <Loading />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>

            <div class="info-form">
              <el-form ref="formRef" :model="doctorInfo" label-width="100px" class="doctor-form" :rules="rules">
                <el-form-item label="姓名：" prop="name">
                  <el-input v-model="doctorInfo.name" disabled="disabled" />
                </el-form-item>

                <el-form-item label="医院：" prop="hospital">
                  <el-input :model-value="hospitalName" placeholder="请选择医院" disabled />
                </el-form-item>

                <el-form-item label="性别：" prop="gender">
                  <el-radio-group v-model="doctorInfo.gender" disabled>
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="手机号：" prop="phone">
                  <el-input v-model="doctorInfo.phone" />
                </el-form-item>

                <el-form-item label="科室：" prop="department">
                  <el-input :model-value="depName" placeholder="请选择科室" disabled />
                </el-form-item>

                <el-form-item label="职称：" prop="title">
                  <el-select v-model="doctorInfo.title" placeholder="请选择职称">
                    <el-option label="主任" value="主任" />
                    <el-option label="副主任" value="副主任" />
                    <el-option label="医师" value="医师" />
                  </el-select>
                </el-form-item>
                <el-form-item label="问诊价格：" prop="price">
                  <el-input-number v-model="doctorInfo.price" :min="1" :max="1000">
                    <template #prefix>
                      <span>￥</span>
                    </template>
                  </el-input-number>
                </el-form-item>
                <el-form-item label="个人简介：" prop="desc">
                  <el-input v-model="doctorInfo.desc" type="textarea" :rows="4" placeholder="请输入个人简介..." maxlength="300"
                    show-word-limit />
                </el-form-item>
              </el-form>
            </div>
            <el-button type="primary" @click="debouncedUpdateDocrorsxx" :loading="submitLoading" :disabled="submitLoading">更改信息</el-button>
          </div>
        </el-tab-pane>

        <!--        <el-tab-pane label="资质信息" name="qualification">-->
        <!--          <div class="qr-code">-->
        <!--            <span class="qr-label">二维码：</span>-->
        <!--            <div class="qr-image">-->
        <!--              <el-image-->
        <!--                  :src="doctorInfo.qrCode || defaultQR"-->
        <!--                  fit="cover"-->
        <!--                  class="qr"-->
        <!--              >-->
        <!--                <template #error>-->
        <!--                  <div class="image-slot">-->
        <!--                    <el-icon><Picture /></el-icon>-->
        <!--                  </div>-->
        <!--                </template>-->
        <!--              </el-image>-->
        <!--            </div>-->
        <!--            <el-upload-->
        <!--                class="qr-uploader"-->
        <!--                action="/api/upload"-->
        <!--                :show-file-list="false"-->
        <!--                :on-success="handleQRSuccess"-->
        <!--            >-->
        <!--              <el-button size="small" type="primary">下载二维码</el-button>-->
        <!--            </el-upload>-->
        <!--          </div>-->
        <!--        </el-tab-pane>-->

        <!--        <el-tab-pane label="患教内容" name="education">-->
        <!--          &lt;!&ndash; 患教内容标签页的内容 &ndash;&gt;-->
        <!--          患教内容-->
        <!--        </el-tab-pane>-->

        <el-tab-pane label="患者信息" name="patients">
          <el-table :data="patientList" style="width: 100%">
            <el-table-column label="患者编号" align="center" width="100" type="index" />
            <el-table-column label="患者姓名" align="center" prop="name" />
            <el-table-column label="联系电话" align="center" prop="phoneNumber" />
            <el-table-column label="性别" align="center" prop="gender">
              <template #default="{ row }">
                {{ row.gender === 1 ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column label="医嘱" align="center" prop="remarks" />
            <el-table-column label="患者状态" align="center" prop="recoveryStatus">
              <template #default="{ row }">
                <el-tag :type="row.recoveryStatus === '1' ? 'success' : 'info'">
                  {{ row.recoveryStatus === '1' ? '已康复' : '治疗中' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- 患者信息标签页的内容 -->
        </el-tab-pane>

        <!--        <el-tab-pane label="患者评价" name="reviews">-->
        <!--          &lt;!&ndash; 患者评价标签页的内容 &ndash;&gt;-->
        <!--        </el-tab-pane>-->

        <!--        <el-tab-pane label="门诊时间" name="schedule">-->
        <!--          &lt;!&ndash; 门诊时间标签页的内容 &ndash;&gt;-->
        <!--        </el-tab-pane>-->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Picture, Back } from '@element-plus/icons-vue'
import { getDoctors, PatientBydoctorId, updateDoctors } from '../../api/doctors/doctors.js'
import { ElMessage } from 'element-plus'

// 添加防抖函数
function debounce(fn, delay = 300) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

const route = useRoute()
const router = useRouter()
const activeTab = ref('personal') // 默认激活"个人资料"标签页

// 表单校验规则
const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  title: [{ required: true, message: '请选择职称', trigger: 'change' }],
  price: [
    { required: true, message: '请输入问诊价格', trigger: 'blur' },
    { type: 'number', min: 1, max: 1000, message: '价格必须在1-1000元之间', trigger: 'blur' }
  ],
  desc: [{ required: true, message: '请输入个人简介', trigger: 'blur' }]
})

// 计算属性，用于处理可能为null的嵌套对象
const hospitalName = computed(() => {
  // 优先使用路由参数
  if (route.params.hospitalName) {
    return decodeURIComponent(route.params.hospitalName)
  }
  
  // 其次使用doctorInfo中的数据
  if (!doctorInfo.value.hospitall) {
    return ''
  }
  
  if (typeof doctorInfo.value.hospitall === 'string') {
    return doctorInfo.value.hospitall
  }
  
  if (typeof doctorInfo.value.hospitall === 'object') {
    return doctorInfo.value.hospitall.name || ''
  }
  
  return ''
})

const depName = computed(() => {
  // 优先使用路由参数
  if (route.params.depName) {
    return decodeURIComponent(route.params.depName)
  }
  
  // 其次使用doctorInfo中的数据
  if (!doctorInfo.value.bigdep) {
    return ''
  }
  
  if (typeof doctorInfo.value.bigdep === 'string') {
    return doctorInfo.value.bigdep
  }
  
  if (typeof doctorInfo.value.bigdep === 'object') {
    return doctorInfo.value.bigdep.name || ''
  }
  
  return ''
})

// 添加一个直接测试API的方法
const testApiDirect = async (docId) => {
  try {
    console.log('直接测试API调用, ID:', docId)
    const response = await fetch(`/api/doctor/doctorXx/${docId}`, {
      method: 'GET',
      headers: {
        'token': localStorage.getItem('token') || '',
        'Content-Type': 'application/json'
      }
    })
    const data = await response.json()
    console.log('直接测试API返回:', data)
    return data
  } catch (error) {
    console.error('直接测试API失败:', error)
    return null
  }
}

const doctorInfo = ref({
  id: null,
  name: '',
  hospitall: {
    id: null,
    name: ''
  },
  gender: 1,
  phone: '',
  bigdep: {
    id: null,
    name: ''
  },
  title: '',
  price: 0,
  desc: '',
  imgurl: '',
  expertise: '',
  introduction: '',
  experience: '',
  avatar: '',
  qrCode: ''
})
/**
 * 患者信息
 */
const patientList = ref([])
const getPatientList = async () => {
  try {
    const doctorId = route.params.id
    const res = await PatientBydoctorId(doctorId)
    console.log(res)
    patientList.value = res.data
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败')
  }
}
// 获取医生信息
const getDoctorInfo = async () => {
  try {
    const id = route.params.id
    console.log('获取医生信息, ID:', id)
    if (!id) {
      console.error('医生ID为空')
      ElMessage.error('医生ID不能为空')
      return
    }
    
    // 先尝试直接测试API
    const testResult = await testApiDirect(id)
    if (testResult) {
      console.log('直接API测试成功，尝试通过getDoctors获取')
    }
    
    const res = await getDoctors(id)
    console.log('医生信息API响应类型:', typeof res)
    console.log('医生信息API响应:', res)
    
    if (res && res.data) {
      // 检查数据格式
      console.log('API返回数据结构:', Object.keys(res))
      console.log('API返回res.data结构:', Object.keys(res.data))
      
      // 创建临时变量处理数据
      const tempData = { ...res.data }
      
      // 显示hospitall和bigdep的类型和值，用于调试
      console.log('tempData.hospitall类型:', typeof tempData.hospitall)
      console.log('tempData.hospitall值:', tempData.hospitall)
      console.log('tempData.bigdep类型:', typeof tempData.bigdep)
      console.log('tempData.bigdep值:', tempData.bigdep)
      
      // 确保hospitall存在且为对象
      if (!tempData.hospitall) {
        console.log('hospitall不存在，创建默认对象')
        tempData.hospitall = { id: null, name: '' }
      } else if (typeof tempData.hospitall === 'string') {
        console.log('hospitall是字符串，尝试解析或创建对象')
        try {
          tempData.hospitall = JSON.parse(tempData.hospitall)
        } catch (e) {
          console.log('无法解析hospitall字符串:', e)
          tempData.hospitall = { id: null, name: tempData.hospitall || '' }
        }
      } else if (typeof tempData.hospitall !== 'object') {
        console.log('hospitall不是对象，创建默认对象')
        tempData.hospitall = { id: null, name: '' }
      }
      
      // 确保bigdep存在且为对象
      if (!tempData.bigdep) {
        console.log('bigdep不存在，创建默认对象')
        tempData.bigdep = { id: null, name: '' }
      } else if (typeof tempData.bigdep === 'string') {
        console.log('bigdep是字符串，尝试解析或创建对象')
        try {
          tempData.bigdep = JSON.parse(tempData.bigdep)
        } catch (e) {
          console.log('无法解析bigdep字符串:', e)
          tempData.bigdep = { id: null, name: tempData.bigdep || '' }
        }
      } else if (typeof tempData.bigdep !== 'object') {
        console.log('bigdep不是对象，创建默认对象')
        tempData.bigdep = { id: null, name: '' }
      }
      
      // 检查处理后的hospitall和bigdep
      console.log('处理后的hospitall:', tempData.hospitall)
      console.log('处理后的bigdep:', tempData.bigdep)
      
      // 处理数据类型，确保gender是数字
      if (tempData.gender && typeof tempData.gender === 'string') {
        tempData.gender = parseInt(tempData.gender)
      }
      
      // 处理数据类型，确保price是数字
      if (tempData.price && typeof tempData.price === 'string') {
        tempData.price = parseFloat(tempData.price)
      }
      
      console.log('处理后的医生信息:', tempData)
      
      // 使用Object.assign保留默认值
      doctorInfo.value = Object.assign({
        id: id,
        name: '',
        hospitall: { id: null, name: '' },
        gender: 1,
        phone: '',
        bigdep: { id: null, name: '' },
        title: '',
        price: 0,
        desc: '',
        imgurl: '',
      }, tempData)
      
      // 使用路由参数强制设置医院和科室信息
      if (route.params.hospitalName) {
        if (!doctorInfo.value.hospitall || typeof doctorInfo.value.hospitall !== 'object') {
          doctorInfo.value.hospitall = {};
        }
        doctorInfo.value.hospitall.name = decodeURIComponent(route.params.hospitalName || '');
        console.log('从路由参数设置医院名称:', doctorInfo.value.hospitall.name);
      }
      
      if (route.params.depName) {
        if (!doctorInfo.value.bigdep || typeof doctorInfo.value.bigdep !== 'object') {
          doctorInfo.value.bigdep = {};
        }
        doctorInfo.value.bigdep.name = decodeURIComponent(route.params.depName || '');
        console.log('从路由参数设置科室名称:', doctorInfo.value.bigdep.name);
      }
      
      console.log('设置后的医生信息:', doctorInfo.value)
      console.log('设置后的医院信息:', doctorInfo.value.hospitall)
      console.log('设置后的科室信息:', doctorInfo.value.bigdep)
    } else {
      console.warn('API返回数据格式不符合预期:', res)
      ElMessage.warning('未获取到医生信息')
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
  }
}
const imageUrl = ref('')

// 头像上传成功
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  doctorInfo.value.imgurl = response.data
  console.log(response);
}
//验证的函数
const beforeAvatarUpload = (rawFile) => {
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
  if (!isImage) {
    ElMessage.error('Avatar picture must be in JPG, PNG, or JPEG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!');
    return false;
  }
  return true;
}
/**
 * 更改医生个人信息
 * @param response
 */
const submitLoading = ref(false);

const updateDocrorsxx = async () => {
  if (!doctorInfo.value.imgurl) {
    ElMessage.error('请上传头像')
    return
  }
  
  if (!formRef.value) return
  
  // 防止重复提交
  if (submitLoading.value) {
    return
  }
  
  try {
    await formRef.value.validate()
    
    // 设置提交状态为加载中
    submitLoading.value = true
    
    const res = await updateDoctors(doctorInfo.value)
    console.log('更新医生信息返回结果:', res)
    
    // 检查响应格式，适配不同返回结构
    if (res.data && res.data.code === 20000) {
      ElMessage.success('更改信息成功')
      getDoctorInfo()
    } else if (res.code === 20000 || res.message === '修改成功') {
      ElMessage.success('更改信息成功')
      getDoctorInfo()
    } else if (res.flag === true && res.message === '修改成功') {
      ElMessage.success('更改信息成功')
      getDoctorInfo()
    } else {
      console.error('更新返回格式异常:', res)
      ElMessage.error('更改信息失败：返回格式异常')
    }
  } catch (error) {
    if (error === false) {
      ElMessage.error('表单验证失败，请检查输入')
      return
    }
    console.error('更改医生信息失败:', error)
    ElMessage.error('更改医生信息失败: ' + (error.message || error))
  } finally {
    // 延迟重置提交状态，确保按钮禁用效果明显
    setTimeout(() => {
      submitLoading.value = false
    }, 500)
  }
}

// 使用防抖包装提交函数
const debouncedUpdateDocrorsxx = debounce(updateDocrorsxx, 300);

// 二维码上传成功
const handleQRSuccess = (response) => {
  doctorInfo.value.qrCode = response.url
  ElMessage.success('二维码上传成功')
}

// 添加表单引用
const formRef = ref(null)

onMounted(() => {
  // 如果路由查询参数中有activeTab值，则使用它
  if (route.query.activeTab) {
    activeTab.value = route.query.activeTab
  }
  
  // 确保获取 hospitalId
  const hospitalId = route.params.hospitalId;
  console.log('获取到的医院ID:', hospitalId); // 添加日志以确认获取到的 hospitalId

  console.log('路由参数:', route.params)
  console.log('查询参数:', route.query)
  
  // 初始化默认值，确保医院和科室显示
  doctorInfo.value = {
    ...doctorInfo.value,
    hospitall: {
      id: null,
      name: route.params.hospitalName ? decodeURIComponent(route.params.hospitalName) : '医院名称'
    },
    bigdep: {
      id: null,
      name: route.params.depName ? decodeURIComponent(route.params.depName) : '科室名称'
    }
  }
  
  // 在页面挂载时立即获取医生数据
  getDoctorInfo()
  getPatientList()
})

// 返回按钮逻辑
const goBack = () => {
  router.go(-1);
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.doctor-info {
  display: flex;
  gap: 40px;
  padding: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar-container {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-form {
  flex: 1;
}

.doctor-form {
  max-width: 600px;
}

.qr-code {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.qr-label {
  font-size: 14px;
  color: #606266;
}

.qr-image {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.qr {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

:deep(.el-tabs__nav) {
  background-color: #fff;
  padding: 0 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
